package com.youlu.campus.admin.auth;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.common.utils.AppContext;
import com.youlu.campus.common.utils.JwtUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
@Order(2)
@WebFilter(filterName = "sesamekefuAuthFilter", urlPatterns = "/sesamekefu/*")
public class SesamekefuAuthFilter extends OncePerRequestFilter {

    private static final String JWT_HEADER_NAME = "campus-admin-token-tkkui";

    @Value("${server.servlet.context-path}")
    private String prefix;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean p=isProtectedUrl(request);
        log.info(":>>> 是否保护的URL:{}",p);
        if (!p && !"OPTIONS".equalsIgnoreCase(request.getMethod())) {
            String token = request.getHeader(JWT_HEADER_NAME);
            if (StringUtils.isEmpty(token)) {
                writeJson(QResult.fail(401, "尊敬的用户,请您请先授权登录,谢谢！")
                        , response);
                log.warn(":>>> 非法访问,没有读取到Authorization头部信息");
                return;
            }
        }
        String token = request.getHeader(JWT_HEADER_NAME);
        Claims claims = JwtUtils.verifyJwt(token);
        if(Objects.isNull(claims)){
            writeJson(QResult.fail(401, "尊敬的用户,请您请先授权登录,谢谢！")
                    , response);
            log.warn(":>>> 非法访问,没有读取到Authorization头部信息");
            return;
        }
        AppContext.release();
        String nick = claims.get("nick").toString();
        log.info("当前登录人昵称 ->{}",nick);
        AppContext.current().setNick(nick);
        String name = claims.get("name").toString();
        AppContext.current().setName(name);
        filterChain.doFilter(request, response);
    }

    private void writeJson(QResult result, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 检查url
     *
     * @param request
     * @return
     */
    public boolean isProtectedUrl(HttpServletRequest request) {


        String uri = request.getRequestURI();
        log.info(":>>> 检查URL isProtectedUrl:{}", uri);
        uri = uri.replace(prefix, "");
        if (uri.contains("swagger") || uri.contains("api-docs") || uri.contains("webjars")) {
            log.info(":>>> URL包含:swagger,api-docs,webjars:{}", uri);
            return true;
        } else if ( uri.startsWith("/topic/")||uri.startsWith("/login")||uri.startsWith("/live")||uri.startsWith("/article")||uri.startsWith("/banner-config")) {
            log.info(":>>> URL包含:public,login,topic:{}", uri);
            return true;
        }
        return false;
    }
}
